package com.zdy.today.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.zdy.model.BaseBean;
import com.zdy.model.HomeListBean;
import com.zdy.today.CallBack;
import com.zdy.today.R;
import com.zdy.today.adapter.HomeAdapter;
import com.zdy.today.api.AskService;
import com.zdy.today.base.BaseActivity;

import java.io.File;
import java.io.FileOutputStream;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@RuntimePermissions
public class MainActivity extends BaseActivity {
    @BindView(R.id.ptr_frame)
    PtrClassicFrameLayout ptrClassicFrameLayout;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.left)
    FrameLayout left;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer_layout;
    private RecyclerAdapterWithHF mAdapter;

    @Override
    protected void init() {
        String str = "1231a";
        String encodeToString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
        System.out.println(encodeToString);
        String decodedString =new String(Base64.decode(encodeToString,Base64.DEFAULT));
        System.out.println(decodedString);
//        MainActivityPermissionsDispatcher.cameraWithCheck(MainActivity.this);

//        MainActivityPermissionsDispatcher.createFileDirWithCheck(this);
        setLeft("", R.drawable.menu, new CallBack() {
            @Override
            public void callBack(Object... params) {
//                MainActivityPermissionsDispatcher.cameraWithCheck(MainActivity.this);
//                Picasso.with(MainActivity.this).load("https://listenwallstreet.com/wp-content/uploads/2017/04/17.png").into(target);
                if(drawer_layout.isDrawerOpen(left)){
                    drawer_layout.closeDrawer(left);
                }else {
                    drawer_layout.openDrawer(left);
                }

            }
        });
        initRefresh();
    }

    //配置intent
    public static Intent getIntent(Context context, int position) {
        Intent intent[] = {
                new Intent(context, VideoViewWelcomeActivity.class),
                new Intent(context, FileDownLoadActivity.class),
                new Intent(context, CaptureActivity.class),
                new Intent(context, DragLayoutActivity.class),
                new Intent(context, ScrollingActivity.class)
        };
        return intent[position];
    }

    Target target = new Target() {

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            File f = new File(getExternalCacheDir(), "listen.jpg");
            if (f.exists()) {
                f.delete();
            }
            try {
                FileOutputStream out = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };

    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    protected String setTitle() {
        return "彩票（排列5）";
    }


    @Override
    protected int getResourceId() {
        return R.layout.activity_refresh;
    }

    HomeAdapter normalAdapter;

    private void initRefresh() {
        normalAdapter = new HomeAdapter(this);
        mAdapter = new RecyclerAdapterWithHF(normalAdapter);
        lv.setLayoutManager(new LinearLayoutManager(this));
        lv.setAdapter(mAdapter);
        setRefreshListener(ptrClassicFrameLayout);
    }

    @Override
    protected void askNetData(Object... params) {
        super.askNetData(params);
        if (netType == 1 || netType == 2) {
            subscribe = AskService.createDemoService(this).getList("pl5-20.json")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this::handlerSuccessPage, this::handlerFailurePage);
        }

    }

    private HomeListBean listBean;

    @Override
    public void addFirstData(BaseBean<? extends BaseBean> baseBean) {
        super.addFirstData(baseBean);
        listBean = (HomeListBean) baseBean;
        normalAdapter.setListBean(listBean.getData());
        mAdapter.notifyDataSetChangedHF();
    }

    @Override
    public void addMoreData(BaseBean<? extends BaseBean> baseBean) {
        super.addMoreData(baseBean);
        HomeListBean bean = (HomeListBean) baseBean;
        listBean.getData().addAll(bean.getData());
        normalAdapter.setListBean(listBean.getData());
        mAdapter.notifyDataSetChangedHF();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void camera() {
        startActivity(new Intent(MainActivity.this, CaptureActivity.class));
    }

//    @OnShowRationale(Manifest.permission.CAMERA)
//    void showRationaleForCamera(final PermissionRequest request) {
//        new AlertDialog.Builder(this)
//                .setMessage("permission_camera_rationale")
//                .setPositiveButton("确定", (dialog, button) -> request.proceed())
//                .setNegativeButton("取消", (dialog, button) -> request.cancel())
//                .show();
//    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "permission_camera_denied", Toast.LENGTH_SHORT).show();
    }

//    @OnNeverAskAgain(Manifest.permission.CAMERA)
//    void showNeverAskForCamera() {
//        Toast.makeText(this, "permission_camera_neverask", Toast.LENGTH_SHORT).show();
//    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void createFileDir() {
        createFilePath("zdyhaha");//创建版本更新app文件夹
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRationaleForWrite(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("permission_write_external_rationale")
                .setPositiveButton("确定", (dialog, button) -> request.proceed())
                .setNegativeButton("取消", (dialog, button) -> request.cancel())
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForWrite() {
        Toast.makeText(this, "permission_write_external_neverask", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void createFileDirDenied() {
        Toast.makeText(this, "permission_write_external_denied", Toast.LENGTH_SHORT).show();
    }

    //创建文件夹，根目录为bjzhidianwuliu，参数folderName为二级目录
    public String createFilePath(String folderName) {
        String apksCacheDir = Environment.getExternalStorageDirectory() + File.separator + "caipiao" + File.separator + folderName;
        File apksFileDir = new File(apksCacheDir);
        if (!apksFileDir.exists()) {
            apksFileDir.mkdirs();
        }
        return apksCacheDir + File.separator;
    }


}
